<!-- 文件上传 -->
<template>
	<uni-file-picker v-model="props.imageList" :auto-upload="false" @select="imgSelect" @delete="imgDelete"
		:readonly="readonly" :limit="limit" :title="title"></uni-file-picker>
</template>

<script lang="ts" setup>
	import { getToken } from "@/utils/storage"
	const props = defineProps({
		readonly: { // 组件只读，不可选择，不显示进度，不显示删除按钮
			type: Boolean,
			default: false
		},
		imageList: {  // 
			type: Array,
			default: function () {
				return [];
			}
		},
		limit: { // 最大选择个数 
			type: Number,
			default: 9
		},
		title: {
			type: String,
			default: ''
		},
		fileMediatype: {
			type: String,
			default: 'image' // image/video/all all只支持 H5 和微信小程序平台
		}
	})
	let token = getToken()
	// 获取上传状态
	async function imgSelect(e) {
		uni.showLoading();
		await uploadImg(e.tempFilePaths)
	}
	async function uploadImg(tempFilePaths) {
		if (!tempFilePaths.length) return;  //如果没有选择图片就退出

		uni.uploadFile({
			url: "https://mini.jingkunkj.com/api/file-upload",
			name: "file",
			files: tempFilePaths,
			formData: {
				'user': 'test'
			},
			header: {
				token: token
			},
			success: (res) => {
				props.imageList.push({
					url: res.fileUrl,
				})
			},
			fail: (error) => {
				// imageValue.value = []
			},
			complete: () => {
				uni.hideLoading();
			}
		})
	}

	// 删除图片
	function imgDelete(err) {
		const num = props.imageList.findIndex(v => v.url === err.tempFilePath);
		props.imageList.splice(num, 1);
	}
</script>

<style lang="scss" scoped>

</style>